# -*- coding: utf-8 -*-
from flask import Blueprint,request,redirect,jsonify
from common.libs.UrlManager import UrlManager
from common.libs.Helper import ops_render,iPagination,getCurrentDate
from common.models.member.Member import Member
from application import app,db
# 蓝图
route_member = Blueprint( 'member_page',__name__ )
# 蓝图定义他的url  以及他的方法名
@route_member.route( "/index" )
def index():
    resp_data={}
    #定义一个 全局变量
    req = request.values
    # 分页:如果p在req中并且 p有效 否则 p=1
    page = int(req['p']) if ('p' in req and req['p']) else 1
    # 查询数据库中的member表
    query = Member.query

    # 搜索的name是mix_kw
    if 'mix_kw' in req:
        # ilike不区分大小写 查询的字段通过字符串的format方法进行传递放到%{0}%中
        query = query.filter(Member.nickname.ilike("%{0}%".format( req['mix_kw'])))

    # 获取状态值
    if 'status' in req and int(req['status'])>-1:
        query = query.filter(Member.status==int(req['status']))

    # ipagenation参数
    page_params = {
        # 查询总的数量
        'total': query.count(),
        # # 当前每一页的大小是多少 PAGE_SIZE默认分页大小
        'page_size': app.config['PAGE_SIZE'],
        'page': page,
        # 展示的每一页是多大 5页 参数在config中base
        'display': app.config['PAGE_DISPLAY'],
        # 将当前页面的参数替换成空
        'url': request.full_path.replace("&p={}".format(page), "")
    }

    # 统一分页的封装类
    pages = iPagination(page_params)
    # 偏移量
    offset = (page - 1) * app.config['PAGE_SIZE']
    # 查询的结果集                           偏移量0-50        每一页大小
    list = query.order_by(Member.id.desc()).offset(offset).limit(app.config['PAGE_SIZE']).all()

    # 结果集统一传送到前台 list循环数据 pages是分页数据
    resp_data['list'] = list
    resp_data['pages'] = pages
    # 将所有req变量值传给变量search_con
    resp_data['search_con'] = req
    resp_data['status_mapping'] = app.config['STATUS_MAPPING']
    resp_data['current']='index'
    return ops_render( "member/index.html",resp_data )
# 每个都有模板
@route_member.route( "/info" )
def info():
    # 获取用户信息
    resp_data ={}
    # 数据多用values 数据少用args
    req= request.args
    # 获取id值，没有就位0
    id = int(req.get("id",0))
    # 统一返回地址
    reback_url=UrlManager.buildUrl("/member/index")
    if id<1:
        return redirect(reback_url)

    # 查询id数据
    info =Member.query.filter_by(id=id).first()
    if not info:
        return redirect(reback_url)

    # 将信息传到前台
    resp_data['info'] =info
    resp_data['current'] ='index'#当前光标是index

    return ops_render( "member/info.html",resp_data )

@route_member.route( "/set",methods = [ "GET","POST" ]  )
def set():
    if request.method == "GET":
        resp_data = {}
        req = request.args
        # 信息编辑功能：编辑昵称
        # 当前页面的id字段 默认值是0
        id = int(req.get("id", 0))
        reback_url = UrlManager.buildUrl("/member/index")
        # 逻辑判断 id<1
        if id < 1:
            return redirect(reback_url)
        info = Member.query.filter_by(id=id).first()
        if not info:
            return redirect(reback_url)
        if info.status != 1:
            return redirect(reback_url)

        resp_data['info'] = info
        resp_data['current'] = 'index'

        return ops_render( "member/set.html",resp_data)
# 定义json返回值 :前端数据去往后端 data返回数据值
    resp={'code':200,'msg':'操作成功','data':{}}
    # 获取提交过来的数据
    req = request.values
    id = req['id'] if 'id' in req else 0
    nickname =req['nickname'] if 'nickname' in req else 0
#     有效性校验
    if nickname is None or len(nickname) <1:
        resp['code']=-1
        resp['data']="请输入复合规范的姓名"
        return  jsonify(resp)

    member_info = Member.query.filter_by(id=id).first()
    if not member_info:
        resp['code'] = -1
        resp['data'] = "指定会员不存在"
        return jsonify(resp)

    # 差如数据库中的信息就是网页渠道的信息
    member_info.nickname =nickname
    member_info.updata_time =getCurrentDate()
    db.session.add(member_info)
    db.session.commit()
    # 提交数据结果集 操作成功（端口200）后跳转js
    return jsonify(resp)

@route_member.route( "/comment" )
def comment():
    return ops_render( "member/comment.html" )

@route_member.route("/ops",methods=["POST"])
def ops():
    # 获取json数据
    resp = { 'code':200,'msg':'操作成功','data':{} }
    req = request.values

    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''

    if not id :
        resp['code'] = -1
        resp['msg'] = "请选择要操作的账号"
        return jsonify(resp)

    if act not in [ 'remove','recover' ]:
        resp['code'] = -1
        resp['msg'] = "操作有误，请重试~~"
        return jsonify(resp)

    member_info = Member.query.filter_by( id = id ).first()
    # 如果member_info不存在
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "指定会员不存在~~"
        return jsonify(resp)
    if act == "remove":
        member_info.status = 0
    elif act == "recover":
        member_info.status = 1
    # 统一更新时间
    member_info.updated_time = getCurrentDate()
    db.session.add(member_info)
    db.session.commit()
    return jsonify( resp )
